//
//  LocalNotification.swift
//  pgy
//
//  Created by vsccw on 2018/12/28.
//  Copyright © 2018 vsccw.com. All rights reserved.
//

import UIKit
import UserNotifications

class LocalNotification: NSObject, UNUserNotificationCenterDelegate {
  
  static let shared = LocalNotification()
  
  override init() {
    super.init()
    if #available(iOS 10.0, *) {
      UNUserNotificationCenter.current().delegate = self
    }
  }
  
  func resetBadge() {
    UIApplication.shared.applicationIconBadgeNumber = 0
  }
  
  func requestPersimission() {
    if #available(iOS 10.0, *) {
      let center = UNUserNotificationCenter.current()
      center.requestAuthorization(options: [.alert, .badge, .sound]) { (isGranted, error) in }
    } else {
      UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil))
    }
  }
  
  func triggerTitleNotification(app: AppInfo) {
    if #available(iOS 10.0, *) {
      let center = UNUserNotificationCenter.current()
      let content = UNMutableNotificationContent()
      if let path = Bundle.main.path(forResource: "avatar", ofType: "png") {
        let url = URL(fileURLWithPath: path)
        if let image = try? UNNotificationAttachment(identifier: "image_URL", url: url, options: nil) {
          content.attachments = [image]
        }
      }
      content.title = app.appName + "更新了"
      content.body = "新版本 " + app.appVersionNo + " 来了"
      content.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "msg.caf"))
      content.badge = 1
      content.userInfo = ["app_key": app.appKey]
      let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
      let date = Date().timeIntervalSinceReferenceDate
      let notification = UNNotificationRequest(identifier: "\(date)", content: content, trigger: trigger)
      center.add(notification, withCompletionHandler: nil)
    } else {
      // Fallback on earlier versions
    }
  }

  
  @available(iOS 12.0, *)
  func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) {
    print(">>>> \(#function)")
  }
  
  @available(iOS 10.0, *)
  func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    if response.actionIdentifier == UNNotificationDefaultActionIdentifier {
      // TODO: - 点击了确定按钮
      completionHandler()
    } else if response.actionIdentifier == UNNotificationDismissActionIdentifier {
      // TODO: - 点击了dismiss按钮
      UIApplication.shared.applicationIconBadgeNumber -= 1
      completionHandler()
    }
    print(">>>> \(response.notification.request.content.userInfo)")
  }
  
  @available(iOS 10.0, *)
  func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    // TODO: - foreground 不可能收到推送，不用管
    completionHandler([.alert, .sound, .badge])
    print(">>>> \(#function)")
  }
}
